<?php
echo "<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css\">";
echo "<script src=\"//code.jquery.com/ui/1.11.2/jquery-ui.js\"></script>";
if(isset($_POST["submit"])) {
	echo "<div id=\"result\">";
	$username = safety(preg_replace("/\([\S\s]*\)/","", $_POST["to"]));
	$title = safety($_POST["title"]);
	$message = safety($_POST["message"]);
	$userQuery = mysqli_query($db, "SELECT id FROM users WHERE username='$username'");
	$date = date("Y-m-d H:i:s");
	if($id = $userQuery->fetch_assoc()){
		$mailQuery = mysqli_query($db, "INSERT INTO messages (toId, fromId, title, message, date) VALUES ('{$id["id"]}', '{$_SESSION["id"]}', '$title', '$message', '$date')");
		if($mailQuery)
			echo "Skickade meddelandet";
		else{
			echo "Okänt Fel";
		}
	}else{
		echo "Användaren kunde inte hittas";
	}
	echo "</div>";
}else{	
	$title = "";
	$toUser = "";
	if(isset($_GET["toId"])) {
		$toQuery = mysqli_query($db, "SELECT firstname, lastname, username FROM users WHERE id={$_GET["toId"]} LIMIT 1");
		if($user = $toQuery->fetch_assoc()) {
			$toUser = "{$user["username"]} ({$user["firstname"]} {$user["lastname"]})";
		}
	}
		
	if(isset($_GET["title"])) {
		$title = $_GET["title"];
	}	
	echo "<div id=\"result\">";
	echo "</div>";
		
	echo "<form class=\"mail\" method=\"GET\"><table>";
	echo "<tr><td>TILL: </td><td><input type=\"text\" name=\"to\" id=\"toField\" value=\"$toUser\" maxlength=\"154\"></td></tr>";
	echo "<tr><td>TITEL: </td><td><input type=\"text\" name=\"title\" value=\"$title\" maxlength=\"50\"></td></tr>";
	echo "<tr><td>MEDDELANDE: </td><td><textarea name=\"message\"></textarea maxlength=\"65535\"></td></tr>";
	echo "<tr><td><input type=\"submit\" name=\"submit\" value=\"Skicka\"></td></tr>";
	echo "</table></form>";
}
?>